package cn.com.hfuu.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mysql.fabric.xmlrpc.base.Array;

import cn.com.hfuu.ExcelUtil;
import cn.com.hfuu.UUIdUtil;
import cn.com.hfuu.ViewExcel;
import cn.com.hfuu.module.role;
import cn.com.hfuu.module.rolemenu;
import cn.com.hfuu.module.user;
import cn.com.hfuu.service.CodeService;
import cn.com.hfuu.service.RoleMenuService;
import cn.com.hfuu.service.RoleService;
import cn.com.hfuu.service.UserService;
import cn.com.hfuu.service.UserroleService;
import cn.com.hfuu.vo.Page;
import cn.com.hfuu.vo.Searchuserlist;

@Controller
@RequestMapping("/user")
public class UserControl {

	@Autowired
	private UserService userService;
	@Autowired
	private CodeService codeservice;
	@Autowired
	private RoleService roleservice;

	@Autowired
	private UserroleService userroleService;

	@Autowired
	private RoleMenuService rolemenuservice;

	@RequestMapping("/changepassword")
	public ModelAndView changePass() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("user/changepassword");
		return mv;

	}

	@RequestMapping("/repass")
	public String rePass(HttpServletResponse resp, String repassword,
			HttpSession session) throws IOException {
		user u = (user) session.getAttribute("user");
		System.out.println(repassword);
		u.setUserPassword(repassword);
		int a = userService.userTimeUpdate(u);
		if (a > 0) {
			return "user/xgmmcg";
		} else {
			return "login/login";
		}

	}

	@RequestMapping("/loginout")
	public void loginOut(HttpSession session, HttpServletResponse resp)
			throws Exception {
		session.invalidate();
		resp.sendRedirect("login/login");
	}

	@RequestMapping("/userlist")
	public ModelAndView userList(HttpServletRequest req) {
		HttpSession s = req.getSession();
		user u = (user) s.getAttribute("user");
		List<role> rolelist = roleservice.selectbyuser(u.getUserId());
		String curr1 = req.getParameter("curr");
		int curr = 1;
		if (curr1 != null) {

			curr = Integer.parseInt(curr1);
		} else if (curr < 1) {
			curr = 1;
		}

		ModelAndView mv = new ModelAndView();
		List<user> userlist = userService.userListpage((curr - 1) * 8, 8);
		for (user user : userlist) {
			if (user.getLastVisit() == "" || user.getLastVisit() == null) {
				user.setLastVisit("无");
			}
		}
		mv.setViewName("user/user");
		mv.addObject("codelist", codeservice.selectbyType("10"));
		mv.addObject("userlist", userlist);
		int pagesize = userService.userList().size();
		mv.addObject("pagesize", pagesize);
		mv.addObject("current", curr);
		return mv;
	}

	@RequestMapping("/userlistad")
	@ResponseBody
	public List<user> userListad() {
		List<user> userliist = new ArrayList<user>();
		userliist = userService.selectall();
		return userliist;
	}

	@RequestMapping("/searchuser")
	@ResponseBody
	public Object searchuser(HttpServletRequest req) {
		Searchuserlist usersearch = new Searchuserlist();
		String username = req.getParameter("username");
		String userId = req.getParameter("userid");
		String state = req.getParameter("userstate");

		int userstate = Integer.parseInt(state);
		String curr1 = req.getParameter("curr");
		System.out.println(curr1);
		int curr = 0;
		if (curr1 != null) {

			curr = Integer.parseInt(curr1);
		} else if (curr < 1) {
			curr = 1;
		}

		List<user> userlist = userService.searchUserpage(username, userId,
				userstate, (curr - 1) * 8, 8);
		for (user user : userlist) {
			if (user.getLastVisit() == "" || user.getLastVisit() == null) {
				user.setLastVisit("无");
			}
		}
		usersearch.setUserlist(userlist);
		int pagesize = userService.searchUser(username, userId, userstate)
				.size();

		usersearch.setCurrent(curr);
		usersearch.setTotal(pagesize);
		if (username != "") {
			usersearch.setUsername(username);
		}
		if (userId != "") {
			usersearch.setUserid(userId);
		}
		if (userstate != -1) {
			usersearch.setUserstate(state);
		} else {
			usersearch.setUserstate("-1");
		}
		System.out.println(usersearch.getCurrent());
		usersearch.toString();
		return usersearch;

	}

	@RequestMapping("/adduser")
	public String adduser() {
		return "user/useradd";
	}

	@RequestMapping("/adduserpro")
	@ResponseBody
	public String useraddPro(HttpServletRequest req) {
		String username = req.getParameter("user");
		if (userService.exitUsername(username) != null) {
			return "error";
		}
		String pass = req.getParameter("password");
		int state = Integer.parseInt(req.getParameter("userState"));
		String id = new UUIdUtil().getUuid();
		user u = new user();
		u.setUserId(id);
		u.setUserName(username);
		u.setUserPassword(pass);
		u.setUserState(state);

		int a = userService.adduser(u);
		System.out.println(u.toString());
		if (a > 0) {
			return "success";

		} else {
			return "false";
		}
	}

	@RequestMapping("/edituser")
	public ModelAndView edituser(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("user/edituser");
		String id = req.getParameter("id");

		user user = userService.selectuserbyid(id);
		mv.addObject("user", user);
		System.out.println(user.getUserState());
		return mv;

	}

	@RequestMapping("/edituserpro")
	@ResponseBody
	public String useredit(user u) {
		System.out.println(u.getUserId());
		if (userService.exitUsernameedit(u.getUserName(), u.getUserId()) != null) {
			return "error";
		}
		if (userService.updateuser(u) > 0) {
			return "success";
		}
		return "false";
	}

	@RequestMapping("/deleteuser")
	@ResponseBody
	public String userdelete(String[] ids) {
		if (userService.deleteuser(ids) > 0) {
			userroleService.deleteuserid(ids);
			return "success";
		}
		return "false";

	}

	/**
	 * 修改用户权限: 1、获取所有权限 2、获取已有权限
	 * 
	 * @param id
	 * @return
	 */
	String id;

	@RequestMapping("edituserrole")
	public ModelAndView edituserrole(String id) {
		ModelAndView mv = new ModelAndView();
		this.id = id;
		mv.setViewName("user/userrole");
		return mv;
	}

	// 开始的权限列表
	List<role> rolemenulist1;

	@RequestMapping("userrolelist")
	@ResponseBody
	public Page rolelisst() {
		List<role> rolelist = roleservice.selectalls();
		rolemenulist1 = userroleService.selectbyuser(id);
		for (role role : rolelist) {
			role.setChecks(false);
			for (role rolemenu : rolemenulist1) {

				if (rolemenu.getRoleId().equals(role.getRoleId())) {
					role.setChecks(true);
				}
			}

		}

		Page page = new Page();
		page.setStart(0);
		page.setLimit(0);
		page.setRoot(rolelist);
		page.setTotal(roleservice.selectalltotal());

		return page;
	}

	/**
	 * 修改用户权限 1、不变 2、插入 3、删除
	 * 
	 * @return
	 */
	@RequestMapping("roleuser")
	@ResponseBody
	public String roleuser(String[] ids) {
		List<role> rolelist = roleservice.selectbiroleid(ids);// 勾选的权限列表

		if (rolemenulist1.size() > 0) {
			userroleService.deletes(rolemenulist1, id);
		}
		if (rolelist.size() > 0) {// 插入
			userroleService.inserts(rolelist, id);
		}

		return "success";

	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping("userxx")
	public ModelAndView userxx(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("user/userxx");
		HttpSession s = req.getSession();
		user u = (user) s.getAttribute("user");
		List<role> rolelist = roleservice.selectbyuser(u.getUserId());
		mv.addObject("user", u);
		mv.addObject("rolelist", rolelist);
		return mv;
	}

	@RequestMapping("/adduserfile")
	public String adduserfile() {
		return "user/useraddfile";
	}

	@RequestMapping("/usermobandown")
	public void usermobandown(HttpServletRequest req,
			HttpServletResponse response) throws Exception {
		String fileName = req.getServletContext().getRealPath("/")
				+ "excel\\用户模板.xls";
		System.out.println(fileName);

		String filename = "用户模板.xls";
		// filename = URLEncoder.encode(filename,"UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes(), "ISO8859-1"));
		BufferedOutputStream out = new BufferedOutputStream(
				response.getOutputStream());
		int len = 0;
		InputStream bis = new BufferedInputStream(new FileInputStream(new File(
				fileName)));
		while ((len = bis.read()) != -1) {
			out.write(len);
			out.flush();
		}
		bis.close();
		out.close();

	}
	
	@RequestMapping(value="userupload",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONArray userupload(MultipartFile file) throws Exception{
		System.out.println("filename:"+file.getOriginalFilename());
		InputStream in = file.getInputStream();
		String res="导入成功";
		try {
			userService.upload(in,file);	
		} catch (Exception e) {
			// TODO: handle exception
			res=e.getMessage();
		}	
		res="[{\"result\":\""+res+"\"}]";
		JSONArray jsonArray = JSONArray.fromObject(res);
		return jsonArray;
	}

	@RequestMapping("export")
	public ModelAndView export(ModelMap map) {

		List<user> uselist = userService.selectall();
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		for (user user : uselist) {
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("编号", user.getUserId());
			map1.put("用户名", user.getUserName());
			if (user.getUserState() == 0) {
				map1.put("状态", "锁定");
			} else {
				map1.put("状态", "正常");
			}
		
			if (user.getLastVisit() == null) {
				map1.put("上次登陆", "无");
			}else{
				map1.put("上次登陆", user.getLastVisit());

			}
			mapList.add(map1);

		}
		String[] title = { "编号", "用户名", "状态", "上次登陆" };
		map.addAttribute("excelList", mapList);
		ViewExcel ve = new ViewExcel(title, "用户信息");
		return new ModelAndView(ve, map);
	}

}
